<?php
/**
 * Created by JetBrains PhpStorm.
 * User: dodasso
 * Date: 7/21/13
 * Time: 6:24 PM
 * To change this template use File | Settings | File Templates.
 */

namespace persistance;

require_once(APP_ROOT . '/modules/log/log.php');
require_once(APP_ROOT . '/modules/log/logCommon.php');
require_once(APP_ROOT . '/modules/persistance/DBConnector.php');
require_once(APP_ROOT . '/modules/common/Errors.php');
require_once(APP_ROOT . '/modules/session/UserDto.php');

use \PDO;
use log\Log;
use log\LogCommon;
use persistance\DBConnector;
use common\Errors;
use session\UserDto;

class UserPersistance {
    /**
     * @var DBConnector
     */
    private $db;

    /**
     * @var boolean
     */
    private $initialized;

    public function __construct() {
        $this->db          = null;
        $this->initialized = false;
    }

    public function __destruct() {
    }

    public function init($db) {
        if((is_null($db)) || !($db instanceof DBConnector)) {
            Log::LOG_PERSISTANCE(LogCommon::logTypeError, "Invalid parameters.");
            return false;
        }

        $this->db          = $db;
        $this->initialized = true;

        return true;
    }

    /**
     * @param $rsa
     * @return bool|UserDto
     */
    private function userFromStatementResult($rsa) {
        if((is_null($rsa)) || (count($rsa) != 1)) {
            Log::LOG_PERSISTANCE(LogCommon::logTypeError, "Invalid parameters.");
            return null;
        }

        $rs = $rsa[0];
        $obj           = new UserDto();
        $obj->id       = intval($rs['id']);
        $obj->username = $rs['username'];
        $obj->password = $rs['password'];
        $obj->role     = intval($rs['role']);
        $obj->status   = intval($rs['status']);

        return $obj;
    }

    /**
     * @param $id
     * @return int
     */
    public function findById($id) {
        if((is_null($id)) || (!is_int($id))) {
            Log::LOG_PERSISTANCE(LogCommon::logTypeError, "Invalid parameters.");
            return array('error'=>Errors::INTEGRAL_ERR_INVALID_PARAMETERS);
        }

        if((!$this->initialized)) {
            Log::LOG_PERSISTANCE(LogCommon::logTypeError, "Not initialized.");
            return array('error'=>ERRORS::INTEGRAL_ERR_PERSISTANCE_NOT_INITIALIZED);
        }

        if(!$this->db->isConnected()) {
            Log::LOG_PERSISTANCE(LogCommon::logTypeError, "Not connected to DB.");
            return array('error'=>Errors::INTEGRAL_ERR_DB_NOT_CONNECTED);
        }

        $query = 'SELECT *' .
                 ' FROM user' .
                 ' WHERE id = ?';
        $rsa = $this->db->query($query,
            array(array($id, PDO::PARAM_INT, null)));

        if($this->db->lastDBErrorCode() != null) {
            Log::LOG_PERSISTANCE(LogCommon::logTypeCritical, 'Unable to execute query. ' .
                implode(' ', $this->db->lastDBErrorInfo()));
            return array('error'=>Errors::INTEGRAL_ERR_PERSISTANCE_UNABLE_TO_READ);
        }
        if(empty($rsa)) {
            Log::LOG_PERSISTANCE(LogCommon::logTypeNotice, 'User not found. Id: ' . $id);
            return array('error'=>Errors::INTEGRAL_ERR_PERSISTANCE_NOT_FOUND);
        }

        $obj = $this->userFromStatementResult($rsa);
        if(is_null($obj)) {
            Log::LOG_PERSISTANCE(LogCommon::logTypeNotice, 'Unable to map user. Id: ' . $id);
            array('error'=>Errors::INTEGRAL_ERR_PERSISTANCE_UNABLE_TO_MAP_OBJECT);
        }

        return array('error'=>Errors::INTEGRAL_ERR_NONE, 'data'=>$obj);
    }

    /**
     * @param $username
     * @return int
     */
    public function findByUsername($username) {
        if((is_null($username)) || (!is_string($username))) {
            Log::LOG_PERSISTANCE(LogCommon::logTypeError, "Invalid parameters.");
            return array('error'=>Errors::INTEGRAL_ERR_INVALID_PARAMETERS);
        }

        if((!$this->initialized)) {
            Log::LOG_PERSISTANCE(LogCommon::logTypeError, "Not initialized.");
            return array('error'=>ERRORS::INTEGRAL_ERR_PERSISTANCE_NOT_INITIALIZED);
        }

        if(!$this->db->isConnected()) {
            Log::LOG_PERSISTANCE(LogCommon::logTypeError, "Not connected to DB.");
            return array('error'=>Errors::INTEGRAL_ERR_PERSISTANCE_NOT_CONNECTED);
        }

        $query = 'SELECT *' .
                 ' FROM user' .
                 ' WHERE username = ?';
        $rsa = $this->db->query($query,
            array(array($username, PDO::PARAM_STR, 255)));

        if($this->db->lastDBErrorCode() != null) {
            Log::LOG_PERSISTANCE(LogCommon::logTypeCritical, 'Unable to execute query. ' .
                implode(' ', $this->db->lastDBErrorInfo()));
            return array('error'=>Errors::INTEGRAL_ERR_PERSISTANCE_UNABLE_TO_READ);
        }
        if((is_null($rsa)) || (empty($rsa))) {
            Log::LOG_PERSISTANCE(LogCommon::logTypeNotice, 'User not found. Username: ' .
                $username);
            return array('error'=>Errors::INTEGRAL_ERR_PERSISTANCE_NOT_FOUND);
        }

        $obj = $this->userFromStatementResult($rsa);
        if(is_null($obj)) {
            Log::LOG_PERSISTANCE(LogCommon::logTypeNotice, 'Unable to map user. Username: ' .
                $username);
            array('error'=>Errors::INTEGRAL_ERR_PERSISTANCE_UNABLE_TO_MAP_OBJECT);
        }

        return array('error'=>Errors::INTEGRAL_ERR_NONE, 'data'=>$obj);
    }
}